//
//  BanBu_TextEditer.m
//  BanBu
//
//  Created by jie zheng on 12-7-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BanBu_TextEditer.h"
#import <QuartzCore/QuartzCore.h>
#import "BanBu_ImageView.h"
#import "BanBu_NavButton.h"
#import "BanBu_ThemeManager.h"
#import "AppDataManager.h"
#import "BanBu_IceBreakerController.h"
#import "BanBu_SearchIceViewController.h"
#import "AppCommunicationManager.h"
@interface BanBu_TextEditer ()

@end

@implementation BanBu_TextEditer

@synthesize textContent = _textContent;


- (id)initWithTitle:(NSString *)myTitle oldText:(NSString *)oldText description:(NSString *)des
{
    self = [super init];
    if (self) {
 
        self.title = myTitle;
        self.view.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
        self.textContent = oldText;
        if([myTitle isEqualToString:NSLocalizedString(@"s0c2", nil)]){
//            myTitle = @"Signature";
            
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSignature:) name:@"selectSignature" object:nil];
            CGSize size = [[NSString stringWithFormat:@"%@-->",NSLocalizedString(@"searchBroadcast", nil)] sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(1000, 40) lineBreakMode:kTextLineBreakByWordWrapping];
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(__MainScreen_Width-10-size.width-10, 190, size.width+10, 40);
            [btn setTitle:[NSString stringWithFormat:@"%@-->",NSLocalizedString(@"searchBroadcast", nil)] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:18];
            [btn addTarget:self action:@selector(searchSignature) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:btn];

        }else if([myTitle isEqualToString:@"Interests and hobbies"]){
//            myTitle = @"Interests";
        }

        UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 120)];
        //textView.delegate = self;
        _inputView = textView;
        
        textView.backgroundColor = [UIColor whiteColor];
        textView.layer.borderColor = [[UIColor grayColor] CGColor];
        textView.layer.borderWidth = 1.0;
        textView.layer.cornerRadius = 6.0;
        textView.textColor = [UIColor darkTextColor];
        textView.font = [UIFont systemFontOfSize:16];
        textView.text = _textContent;
        [self.view addSubview:textView];
        [textView release];
        
        NSLog(@"%@",myTitle);
        if([myTitle isEqualToString:NSLocalizedString(@"s2c1", nil)]||[myTitle isEqualToString:NSLocalizedString(@"s2c0", nil)])
        {
            UIView *aView = [[UIView alloc] init];
            [self getInfoOnlineWithTitle:myTitle];
            //            NSLog(@"%@",myTitle);
            aView.frame = CGRectMake(10, 190, 300, __MainScreen_Height - 190);
            [self.view addSubview:aView];
            self.editTextView = aView;
            [aView release];
            NSMutableArray *array = [[NSMutableArray alloc] init];
            self.editInfo = array;
            [array release];
            
            UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            act.center = CGPointMake(__MainScreen_Width/2, (__MainScreen_Height+190)/2);
            [self.view addSubview:act];
            act.tag = 12;
            [act startAnimating];
            [act release];
        }
        else if ([myTitle isEqualToString:NSLocalizedString(@"s0c2", nil)])
        {
            UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(10, 230, 300, __MainScreen_Height-280)];
            table.delegate = self;
            table.dataSource = self;
            table.backgroundColor = [UIColor clearColor];
            _tableView = table;
            [self.view addSubview:table];
            [table release];
            [self getInfoOnlineWithTitle:myTitle];
            NSMutableArray *array = [[NSMutableArray alloc] init];
            self.editInfo = array;
            [array release];
            
            UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            act.center = CGPointMake(__MainScreen_Width/2, (__MainScreen_Height-280)/2+230);
            [self.view addSubview:act];
            act.tag = 12;
            [act startAnimating];
            [act release];
        }
        else
        {
            [_inputView becomeFirstResponder];
        }
        
        UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 135, 300, 40)];
        infoLabel.numberOfLines = 0;
        infoLabel.textAlignment = kTextAlignmentCenter;
        infoLabel.backgroundColor = [UIColor clearColor];
        infoLabel.textColor = [UIColor grayColor];
        infoLabel.font = [UIFont systemFontOfSize:15];
        infoLabel.text = des;
        [self.view addSubview:infoLabel];
        [infoLabel release];
        


    }
    return self;
}

-(void)changeSignature:(NSNotification *)notification
{
    NSString *saytext = (NSString *)[notification object];
    _inputView.text = saytext;
}
- (void)searchSignature
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    [parDic setValue:@"text" forKey:@"kind"];
    [parDic setValue:@"sayme" forKey:@"keyword"];
//    [parDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"country"];
    BanBu_IceBreakerController  *text = [[BanBu_IceBreakerController alloc]init];
    text.title = NSLocalizedString(@"s0c2", nil);
    text.parDic = parDic;
    text.isFromProfile = YES;
    [self.navigationController pushViewController:text animated:YES];
    [text release];
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:219.0/255 green:218.0/255 blue:212.0/255 alpha:1.0];

    CGFloat btnLen1 = [NSLocalizedString(@"confirmNotice", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
    BanBu_NavButton *deleteButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    deleteButton.position = ButtonPositionRight;
    deleteButton.frame=CGRectMake(0, 0, btnLen1+20, 30);
    deleteButton.tag = 101;
    [deleteButton addTarget:self action:@selector(delete) forControlEvents:UIControlEventTouchUpInside];
    [deleteButton setTitleEdgeInsets:UIEdgeInsetsMake(3, 2, 2, 2)];
    [deleteButton setTitle:NSLocalizedString(@"confirmNotice", nil) forState:UIControlStateNormal];
    deleteButton.titleLabel.font = [UIFont systemFontOfSize:14];
    UIBarButtonItem *delItem = [[[UIBarButtonItem alloc] initWithCustomView:deleteButton] autorelease];
    self.navigationItem.rightBarButtonItem = delItem;
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[ThemeManager getThemeImage:@"table_backimage.jpg"]];
    
    //2014年09月28日14:29:14 返回默认是放弃修改 yinlinlin
//    BanBu_NavButton *btn_return=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
////    [btn_return addTarget:self action:@selector(delete) forControlEvents:UIControlEventTouchUpInside];
//    btn_return.frame=CGRectMake(0, 0, btnLen1+20, 30);
//    //    [btn_return setTitleEdgeInsets:UIEdgeInsetsMake(3, 9, 2, 2)];
//    [btn_return setTitle:NSLocalizedString(@"returnButton", nil) forState:UIControlStateNormal];
//    btn_return.titleLabel.font = [UIFont systemFontOfSize:14];
//    UIBarButtonItem *bar_itemreturn=[[[UIBarButtonItem alloc] initWithCustomView:btn_return] autorelease];
//    self.navigationItem.leftBarButtonItem = bar_itemreturn;
//    [btn_return release];

}
-(void)getInfoOnlineWithTitle:(NSString *)title
{
    if([title isEqualToString:NSLocalizedString(@"s2c1", nil)])
    {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"lovego",@"kindof", nil];
        [AppComManager getBanBuData:BanBu_Get_Infor_Edit_Online par:dic delegate:self];
    }
    else if([title isEqualToString:NSLocalizedString(@"s2c0", nil)])
    {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"liked",@"kindof", nil];
        [AppComManager getBanBuData:BanBu_Get_Infor_Edit_Online par:dic delegate:self];
    }
    else if([title isEqualToString:NSLocalizedString(@"s0c2", nil)])
    {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[MyAppDataManager getLanguageSubmitToServer],@"lang", nil];
        [AppComManager getBanBuData:BanBu_Get_Infor_Status_Online par:dic delegate:self];
    }
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    self.textContent = nil;

    
    
}

-(void)delete{
    [self.navigationController popViewControllerAnimated:YES];
    if(![_inputView.text isEqualToString:_textContent])
    {
        if([_delegate respondsToSelector:@selector(banBuTextEditerDidChangeValue:forItem:)]){
            if([self.title isEqualToString:@"Signature"]){
                self.title = @"Personal signature";
            }else if([self.title isEqualToString:@"Interests"]){
                self.title = @"Interests and hobbies";
            }
            [_delegate banBuTextEditerDidChangeValue:_inputView.text forItem:self.title];
        }
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

}

- (void)dealloc
{
    if([self.title isEqualToString:NSLocalizedString(@"s0c2", nil)])
    {
        [[NSNotificationCenter defaultCenter]removeObserver:self name:@"selectSignature" object:nil];
    }
    if(_editTextView||_tableView)
    {
        [_editTextView release],_editTextView = nil;
        [_editInfo release],_editInfo = nil;
    }
    [AppComManager cancalHandlesForObject:self];
    [_textContent release],_textContent= nil;
    [super dealloc];
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_inputView resignFirstResponder];
}
#pragma -
#pragma UITextView delegate methods


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    NSLog(@"%@",resDic);
    UIActivityIndicatorView *act = (UIActivityIndicatorView *)[self.view viewWithTag:12];
    [act stopAnimating];
    [act removeFromSuperview];
    if(error)
    {
        
    }
    else
    {
        if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Infor_Edit_Online])
        {
            if([[resDic valueForKey:@"ok"] boolValue])
            {
                [self.editInfo addObjectsFromArray:[resDic valueForKey:@"list"]];
                if(self.editTextView)
                {
                    CGFloat lineHeight = 0;
                    for (int i=0; i<[[resDic valueForKey:@"list"] count]; i++)
                    {
                        UIButton *aButton=[UIButton buttonWithType:UIButtonTypeCustom];
                        aButton.tag=i;
                        aButton.frame=CGRectMake(i%3*100, i/3*45, 100, 20);
                        lineHeight = i/3*45;
                        [aButton setTitle:[[resDic valueForKey:@"list"] objectAtIndex:i] forState:UIControlStateNormal];
                        [aButton setTitleColor:[UIColor colorWithRed:(arc4random()%256/256.0) green:(arc4random()%256/256.0) blue:(arc4random()%256/256.0) alpha:1.0] forState:UIControlStateNormal];
                        aButton.backgroundColor=[UIColor clearColor];
                        [_editTextView addSubview:aButton];
                        [aButton addTarget:self action:@selector(placeSelect:) forControlEvents:UIControlEventTouchUpInside];
                    }
                }
            }
        }

        if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Infor_Status_Online])
        {
            if([[resDic valueForKey:@"ok"] boolValue])
            {
                 [self.editInfo addObjectsFromArray:[resDic valueForKey:@"list"]];
                [_tableView reloadData];
            }
        }
    }
}
-(void)placeSelect:(UIButton *)sender
{
    NSMutableString *s = [NSMutableString stringWithString:_inputView.text];
    NSString *addString = [NSString stringWithFormat:@"%@、",[self.editInfo objectAtIndex:sender.tag]];
    if([s rangeOfString:addString].location == NSNotFound)
        [s appendString:addString];
    _inputView.text = s;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"editCellIndentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = [_editInfo objectAtIndex:indexPath.row];
    NSLog(@"%@",cell.textLabel.font);
    return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _editInfo.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    UITableView *cell = [tableView cellForRowAtIndexPath:indexPath];
    CGFloat h = [[_editInfo objectAtIndex:indexPath.row] sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(300, 400) lineBreakMode:kTextLineBreakByWordWrapping].height+20;
    return h;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSMutableString *s = [NSMutableString stringWithString:_inputView.text];
//    NSString *addString = [NSString stringWithFormat:@"%@",[self.editInfo objectAtIndex:indexPath.row]];
//    if([s rangeOfString:addString].location == NSNotFound)
//        [s appendString:addString];
    _inputView.text = [self.editInfo objectAtIndex:indexPath.row];
}
@end
